#pragma once
#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>
#include "log.hpp"
#include"NoCopy.hpp"

class Epoller : public NoCopy
{
public:
    Epoller()
    {
        epfd_ = epoll_create(128);
        if(epfd_> 0) lg(Info,"epoll create success,fd is: %d",epfd_);
    }

    void EpollerUpdate(int ops, int sock, uint32_t event)
    {
        int n;
        if (ops == EPOLL_CTL_DEL)
        {
            int n = epoll_ctl(epfd_, ops, sock, nullptr);
            if (n < 0)
            {
                lg(Error, "epoll_ctl delete error,fd is: %d", sock);
            }
        }
        else
        {
            struct epoll_event epo_event;
            epo_event.events = event;
            epo_event.data.fd = sock;
            int n = epoll_ctl(epfd_, ops, sock, &epo_event);
            if (n < 0)
            {
                lg(Error, "epoll_ctl error,fd is: %d", sock);
            }
        }
    }

    int EpollerWait(struct epoll_event events[], int num,int timeout = 3000)
    {
        int n = epoll_wait(epfd_, events, num, timeout);
        if (n < 0)
        {
            lg(Error, "epollwait error");
        }
        return n;
    }

    ~Epoller()
    {
        if (epfd_ > 0)
        {
            ::close(epfd_);
        }
    }

private:
    int epfd_;
};